package com.bootdo.system.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.app.common.msg.Response;
import com.bootdo.app.service.UserGroupBuyService;
import com.bootdo.app.vo.miniprogram.GroupBuyJoinerVo;
import com.bootdo.common.utils.KswUtils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.TbGroupBuying;
import com.bootdo.system.domain.TbOrder;
import com.bootdo.system.domain.TbSvip;
import com.bootdo.system.domain.TbViporder;
import com.bootdo.system.domain.TbWallet;
import com.bootdo.system.domain.TbWithdrawal;
import com.bootdo.system.domain.TbWxUserMeetVip;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.dto.GmspDto;
import com.bootdo.system.dto.ProductDto;
import com.bootdo.system.service.DeptService;
import com.bootdo.system.service.KswService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.ProductService;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxUserService;
import com.bootdo.system.service.impl.KswServiceImpl;

/**
 * 
 * @author sw
 *	会员管理
 */
@RequestMapping("/hygl")
@Controller
public class MembersController {
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private KswService kswService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private UserGroupBuyService userGroupBuyService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private UserService userService;
	
	
	String prefix = "system/hygl";
	
	@GetMapping()
	String task() {
		return prefix + "/hygl";
	}
	
	@GetMapping("jcLog")
	String jcLog() {
		return prefix + "/jcLog";
	}
	
	@GetMapping("jcLog2ph")
	String jcLog2ph() {
		return prefix + "/jcLog2ph";
	}
	
	@GetMapping("lqhy")
	String lqhy() {
		return prefix + "/lqhy";
	}
	
	@GetMapping("yqgl")
	String yqgl() {
		return prefix + "/yqgl";
	}
	@GetMapping("/yqrNum")
	String rwzsIndex(Integer id,Model model) {
		model.addAttribute("id", id);
		return prefix + "/yqgl2user";
	}
	
	@ResponseBody
	@RequestMapping("/list")
	public PageUtils gzhConfigList(@RequestParam Map<String, Object> params) {
		UserDO user = ShiroUtils.getUser();
		if(user.getUserId() != 1L) {
			List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
			boolean falg=false;
			for (RoleDO role : list2) {
				if(role.getRoleId() == 59L) {
					falg=true;
				}
			}
			if(falg) {
				params.put("deptId", user.getDeptId());
			}else {
				params.put("sid", user.getUserId());
			}
		}
		Query query = new Query(params);
		 List<TbWxuser> list = wxUserService.list(query);
		 List<TbWxuser> res = new ArrayList<TbWxuser>();
		 for (TbWxuser tbWxuser : list) {
			 String balance = tbWxuser.getBalance();
			 Integer wxuserId = tbWxuser.getWxuserId();
			 if(wxuserId != null && wxuserId > 1) {
				 TbWxuser byId = wxUserService.getById(wxuserId);
				 if(byId != null) {
					 tbWxuser.setWxName2(byId.getNickname()+" ( ID : "+byId.getId()+" ) ");
				 }
			 }
			 tbWxuser.setBalance(getDouble2String2(balance)+"");
			 res.add(tbWxuser);
		}
		 int count = wxUserService.count(query);
		 PageUtils pageUtil = new PageUtils(res, count);
		 return pageUtil;
	}
	
	@ResponseBody
	@RequestMapping("/list2Yq")
	public PageUtils list2Yq(@RequestParam Map<String, Object> params) {
		UserDO user = ShiroUtils.getUser();
		if(user.getUserId() != 1L) {
			List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
			boolean falg=false;
			for (RoleDO role : list2) {
				if(role.getRoleId() == 59L) {
					falg=true;
				}
			}
			if(falg) {
				params.put("deptId", user.getDeptId());
			}else {
				params.put("sid", user.getUserId());
			}
		}
		Query query = new Query(params);
		 List<TbGroupBuying> list = userGroupBuyService.list(query);
		 List<TbGroupBuying> res=new ArrayList<TbGroupBuying>();
		 for (TbGroupBuying gb : list) {
			 TbWxuser byId = wxUserService.getById(gb.getCreateUserId());
			 if(byId != null) {
				 gb.setWxInfo(byId.getNickname()+" ( ID : "+byId.getId()+" ) ");
			 }
			 TbSvip byStoId = productService.getByStoId(Integer.valueOf(gb.getGoodsId()));
			 if(byStoId != null) {
				 gb.setGoodsInfo(byStoId.getTitle());
			 }
			 gb.setYqrNum(userGroupBuyService.yqrNum(gb.getId()));
			 res.add(gb);
		}
		 int count = userGroupBuyService.count(query);
		 PageUtils pageUtil = new PageUtils(res, count);
		 return pageUtil;
	}
	
	@ResponseBody
	@RequestMapping("/list2yqUser")
	public List<TbWxuser> list2yqUser(Integer ggid) {
		List<TbWxuser>  res=new ArrayList<TbWxuser>();
		List<GroupBuyJoinerVo> yqUser = userGroupBuyService.getYqUser(ggid);
		for (GroupBuyJoinerVo groupBuyJoinerVo : yqUser) {
			String userId = groupBuyJoinerVo.getUserId();
			TbWxuser byId = wxUserService.getById(Integer.valueOf(userId));
			res.add(byId);
		}
		 return res;
	}
	
	private Double getDouble2String2(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	
	@ResponseBody
	@RequestMapping("/listLqhy")
	public PageUtils listLqhy(@RequestParam Map<String, Object> params) {
		UserDO user = ShiroUtils.getUser();
		List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
		boolean falg=false;
		for (RoleDO role : list2) {
			if(role.getRoleId() == 59L) {
				falg=true;
			}
		}
		if(falg) {
			params.put("deptId", user.getDeptId());
		}else {
			params.put("sid", user.getUserId());
		}
		 Query query = new Query(params);
		 List<TbWxUserMeetVip> list = wxUserService.listLqhy(query);
		 int count = wxUserService.countLqhy(query);
		 PageUtils pageUtil = new PageUtils(list, count);
		 return pageUtil;
	}
	
	@ResponseBody
	@RequestMapping("/listJc")
	public PageUtils gzhListJc(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		UserDO user = ShiroUtils.getUser();
		List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
		boolean falg=false;
		for (RoleDO role : list2) {
			if(role.getRoleId() == 59L) {
				falg=true;
			}
		}
		String offset = (String) params.get("offset");
		String limit = (String) params.get("limit");
		params.put("offset", Integer.valueOf(offset));
		params.put("limit", Integer.valueOf(limit));
		List<Map<String,Object>> list=null;
		int count=0;
		if(falg) {
			params.put("deptId", user.getDeptId());
			list = wxUserService.listJc2Dept(params);
			count= wxUserService.countJc2Dept(params);
		}else {
			params.put("userId", user.getUserId());
			list = wxUserService.listJc(params);
			count= wxUserService.countJc(params);
		}
		if(list != null) {
			for (Map<String, Object> map : list) {
				Integer wxId = (Integer) map.get("wx_id");
				TbWxuser byId = wxUserService.getById(wxId);
				map.put("wxName", byId.getNickname() +"( ID : "+ wxId+" )");
			}
		}
		 PageUtils pageUtil = new PageUtils(list, count);
		 return pageUtil;
	}
	
	
	@ResponseBody
	@RequestMapping("/listJc2ph")
	public PageUtils listJc2ph(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		UserDO user = ShiroUtils.getUser();
		List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
		boolean falg=false;
		boolean supFlag = false;
		for (RoleDO role : list2) {
			if(role.getRoleId() == 59L||role.getRoleId()==1L) {
				falg=true;
				if(role.getRoleId()==1L){
					supFlag =true;
				}
			}
		}
		String offset = (String) params.get("offset");
		String limit = (String) params.get("limit");
		params.put("offset", Integer.valueOf(offset));
		params.put("limit", Integer.valueOf(limit));
		List<Map<String,Object>> list=null;
		int count=0;
		if(falg) {
            if(!supFlag) {
				params.put("deptId", user.getDeptId());
			}
			list = wxUserService.listJc2Dept2(params);
			count= wxUserService.countJc2Dept2(query);
		}else {
			params.put("userId", user.getUserId());
			list = wxUserService.listJc2(params);
			count= wxUserService.countJc2(query);
		}
		  
		 PageUtils pageUtil = new PageUtils(list, count);
		 return pageUtil;
	}
	
	
	@GetMapping("/edit/{id}")
	String edit(Model model,@PathVariable("id") Integer id) {
		TbWxuser us = wxUserService.getById(id);
		model.addAttribute("us", us);
		return prefix+"/edit";
	}
	
	
	@PostMapping("/update")
	@ResponseBody
	R update(TbWxuser table) {
		if (wxUserService.insert2update(table) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	
	@PostMapping("/remove")
	@ResponseBody
	R removeWx(Integer id) {
		if (wxUserService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemoveWx(@RequestParam("ids[]") Integer[] wxIds) {
		int r = wxUserService.batchremove(wxIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	
	@PostMapping("/lqhyByGoodsId")
	@ResponseBody
	R lqhyByGoodsId(Integer id,Integer goodsId,String phone,Integer wxUserId) {
		ProductDto productDto = getPrice(goodsId);
		if(productDto != null) {
			 int stock_state = productDto.getStock_state();
			   double price = productDto.getPrice();
			   if(stock_state == 2) {
				   return R.error("没有库存");
			   }else  if(stock_state == 1) {
				   TbWxuser byId2 = wxUserService.getById(wxUserId);
				   UserDO userDO = userService.get(Long.valueOf(byId2.getSid()));
					String balanceuc = userDO.getBalance();
					Double balanceu = getDouble2String(balanceuc);
					if(balanceu < price) {
						return R.error("商家余额不足");
					}else {
						userDO.setBalance((balanceu-price)+"");
						userService.update4(userDO);
						 String customer_id=KswUtils.customer_id;
							String key=KswUtils.ksw_key;
							SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
							String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
							 TreeMap<String, String> treeMap = new TreeMap<String, String>();
							   treeMap.put("customer_id" , customer_id);
							   treeMap.put("timestamp" , timestamp);
							GmspDto gmspDto = kswService.getGmspDto(goodsId, phone, 1, key, treeMap);
							if (gmspDto != null) {
								TbWxUserMeetVip table=new TbWxUserMeetVip();
								table.setId(id);
								table.setStatus(1);
								if(wxUserService.updateLqhy(table) > 0) {
									TbWxuser byId = wxUserService.getById(wxUserId);
									TbViporder byOrdId =new TbViporder();
									byOrdId.setProfit("-"+price);
									byOrdId.setOid(gmspDto.getOrder_id());
									byOrdId.setOpenid(byId.getOpenidXcx());
									byOrdId.setRechargeAccount(phone);
									byOrdId.setQuantity("1");
									byOrdId.setTitle("签到送会员");
									byOrdId.setDirect("0");
									byOrdId.setProductId(goodsId+"");
									byOrdId.setStatus(2);
									orderService.insert2updateSvip(byOrdId);
									return R.ok();
								}
							}
					}
			   }
		}
		return R.error();
	}
	
	private ProductDto getPrice(Integer productid) {
		String customer_id=KswUtils.customer_id;
		String key=KswUtils.ksw_key;
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhss");//设置日期格式
		String timestamp = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
		 TreeMap<String, String> treeMap = new TreeMap<String, String>();
		   treeMap.put("customer_id" , customer_id);
		   treeMap.put("timestamp" , timestamp);
		   ProductDto gmspDto = kswService.getSpxx(productid, key, treeMap);
		   return gmspDto;
	}
	
	private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}

}
